package com.example.demo.service.impl;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.example.demo.exception.ServiceException;
import com.example.demo.mapper.AdminMapper;
import com.example.demo.pojo.Admin;

import com.example.demo.pojo.request.AdminPageRequest;

import com.example.demo.pojo.request.PasswordRequest;
import com.example.demo.service.IAdminService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class AdminServiceImpl implements IAdminService {
    private static final String DEFAULT_PASS="123";
    private static final String PASS_SALT="gege";
    @Autowired
    private AdminMapper adminManager;
    //查询全部
    @Override
    public List<Admin> list() {
        List<Admin> adminList = adminManager.list();
        return adminList;
    }

    //分页查询
    @Override
    public PageInfo<Admin> page(AdminPageRequest adminPageRequest) {
        //这一句可以省略sql的分页语句
        PageHelper.startPage(adminPageRequest.getPageNum(),adminPageRequest.getPageSize());
        List<Admin> adminList = adminManager.page(adminPageRequest);
        //将每一页的数据返回
        return new PageInfo<>(adminList);
    }

    //添加数据
    @Override
    public void save(Admin admin) {
        if(StrUtil.isBlank(admin.getPassword())) {
            admin.setPassword(DEFAULT_PASS);
        }
        //设置m5加密，加盐（防止密码过于简单，即使加密也易破解）
        admin.setPassword(SecureUtil.md5(admin.getPassword()+PASS_SALT));
        admin.setCreateTime(new Date());
        adminManager.save(admin);
    }

    //回写信息
    @Override
    public Admin getUser(Integer id) {
        Admin admin = adminManager.getUser(id);
        return admin;
    }

    //编辑数据
    @Override
    public void getIDUser(Admin admin) {
        admin.setUpdateTime(new Date());
        adminManager.getUserByID(admin);
    }

    //删除数据
    @Override
    public void delete(Integer id) {
        adminManager.delete(id);
    }

    //修改密码
    @Override
    public void changePassword(PasswordRequest passwordRequest) {
        //加密后传入数据库
        passwordRequest.setNewPass(SecureUtil.md5(passwordRequest.getNewPass()+PASS_SALT));
        adminManager.changePassword(passwordRequest);

    }
}
